/**
 * Created by Weizehua on 2017/1/22.
 */
import {HandlerClass, Handle, ParamType, Validators} from "../Core/Dispatcher/Dispatcher";
import {CaptchaService} from "../Captcha/CaptchaService";
import {UserService} from "../User/UserService";
import {tr} from "../Core/Localization/Translator";
import {Geetest} from "../../Geetest/Geetest";
import {Injector} from "ts.di";

@HandlerClass()
export class GeetestHandler {
    constructor(private captchaService: CaptchaService, private geetest: Geetest,
                private userService: UserService) {
    }

    @Handle('/Geetest/register')
    async geetestRegister() {
        let res = await this.geetest.register();
        res.success = true;
        return res;
    }

    @Handle('/Geetest/validate')
    @ParamType({
        phone: String,
        gtValidate: Object,
    })
    @Validators({
        phone: [
            UserService.isPhoneString,
            async phone => await Injector.get(UserService).isPhoneRegistered(phone) ? tr`phone number : ${phone} already registered!` : true
        ]
    })
    async geetestValidate(param: any) {
        let validateParam = {
            challenge: param.gtValidate.geetest_challenge,
            validate: param.gtValidate.geetest_validate,
            seccode: param.gtValidate.geetest_seccode
        };
        let res = await this.geetest.validate(validateParam);
        if (!res)
            return "validate failed";
        return {success: true, captchaInfo: await this.captchaService.sendCaptcha(param.phone)}
    }
}
